home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 9791 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.8 KB

  1. Path: dawn.mmm.com!news
  2. From: kjhopps@mmm.com (Kevin J Hopps)
  3. Newsgroups: comp.lang.c++,rb.technical
  4. Subject: Re: Can copy constructor and operator= share code?
  5. Followup-To: comp.lang.c++,rb.technical
  6. Date: 4 Mar 1996 15:10:03 GMT
  7. Organization: 3M - St. Paul, MN  55144-1000 US
  8. Distribution: world
  9. Message-ID: <4hf14b$69q@dawn.mmm.com>
  10. References: <4h2kcn$40d@rap.SanDiegoCA.ATTGIS.COM> <4h525l$pja@rap.SanDiegoCA.ATTGIS.COM>
  11. Reply-To: kjhopps@mmm.com
  12. X-Newsreader: TIN [version 1.2 PL2]
  13.  
  14. Jake Le (dle@costello.SanDiegoCA.ATTGIS.COM) wrote:
  15. > Boris,
  16.  
  17. > You can call the operator= in your copy constructor.
  18.  
  19. > Here is an example:
  20.  
  21. > class CFoo {
  22.  
  23. > public:
  24. >         CFoo() { m_iSize = 0; };
  25. >         CFoo(const CFoo &foo)
  26. >         {
  27. >         // Call the operator=
  28. >                 this->operator=(foo);
  29. >         };
  30.  
  31. >         CFoo& operator=(const CFoo &foo)
  32. >         {
  33. >                 m_iSize = foo.m_iSize;
  34. >                 return *this;
  35. >         };
  36.  
  37. >         void Print() { cout << "Size = " << m_iSize << endl; };
  38. >         void SetSize(int size) { m_iSize = size; };
  39.  
  40. >         int m_iSize; // Hungarian notation
  41. > };
  42.  
  43. Be careful to initialize your members in the copy constructor before
  44. you call operator=().  If CFoo contained a pointer to dynamically
  45. allocated memory, this would not work well at all.  Also, be sure
  46. in operator=() to handle the case where the object is being assigned
  47. to itself:
  48.     if (&foo != this) {
  49.     // do the work
  50.     }
  51. --
  52. Kevin J. Hopps                  e-mail: kjhopps@mmm.com
  53. 3M Company                      phone:  (612) 737-4643
  54. 3M Center, Bldg. 235-2D-57      fax:    (612) 737-2700
  55. St. Paul, MN 55144-1000         Opinions are my own.  I don't speak for 3M.
  56.     But 3M speaks for me -- I did not write the following line:
  57.  
  58. Opinions expressed herein are my own and may not represent those of 3M.
  59.